<template>
    <view class="contact">
        <uni-search-bar v-model="searchValue" placeholder="输入姓名或号码">
        </uni-search-bar>
        <view class="container">
            <uni-indexed-list
                :options="contactList"
                :showSelect="false"
                @click="bindClick"></uni-indexed-list>
        </view>
    </view>
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import {ref, reactive, computed, getCurrentInstance, onMounted } from "vue"
import Interact from '@/utils/interact';
import Pinyin from '@/utils/ChinesePY.js';

type contactType = {
    letter: string,
    id: string,
    name: string,
    mobile: string,
    type: string
}
type indexListSourceType = {
    letter: string,
    data: contactType[]
}
type IndexListType = {
    letter: string,
    data: string[]
}


const contactSourceList = ref<indexListSourceType[]>([])
const contactSearchList = computed(() => {
    let newList = contactSourceList.value.map(item => {
        let newPhoneList = []
        if(searchValue.value) {
            newPhoneList = item.data.filter(i => i.name.includes(searchValue.value) || i.mobile.includes(searchValue.value))
        } else {
            newPhoneList = item.data
        }
        return {
            letter: item.letter,
            data: newPhoneList
        }
    })
    return newList.filter(i => i.data.length > 0)

})
const contactList = computed(() => {
    let newList = contactSearchList.value.map(item => {
        return {
            letter: item.letter,
            data: item.data.map(i => i.name + '：' + i.mobile)
        }
    })
    return newList.filter(i => i.data.length > 0)
})


const searchValue = ref('')

onLoad((options) => {
    getContacts()



})

let eventChannel: any;
onMounted(() => {
    try {
        const instance = (getCurrentInstance() as any).proxy
        eventChannel = instance.getOpenerEventChannel();
    } catch(err) {
        console.log(err);

    }
})


const bindClick = (phone: any) => {
    // console.log(phone);
    // console.log(phone.item.itemIndex);
    let letterIndex = contactSearchList.value.findIndex(item => item.letter == phone.item.key)
    let phoneInfo = contactSearchList.value[letterIndex].data[phone.item.itemIndex - letterIndex]
    console.log(phoneInfo);
    eventChannel.emit('contactInfo', phoneInfo);
    uni.navigateBack()
}

const getContacts = () => {
    const platform = uni.getSystemInfoSync().platform;
    console.log(platform);

    if (platform === 'android') {
        plus.android.requestPermissions(
            ['android.permission.READ_CONTACTS'],
            (resultObj) => {
                const result = resultObj.granted;
                if (result.indexOf('android.permission.READ_CONTACTS') !== -1) {
                    getContactsHandle();
                } else {
                    Interact.toast('您拒绝了通讯录权限，请在设置中开启');
                }
            },
            (error) => {
                console.log('请求权限失败: ' + JSON.stringify(error));
                Interact.modal({
                    title: '权限请求失败',
                    message: '应用需要读取通讯录权限才能为您提供更好的服务，请在设置中授予该权限。'
                });
            }
        );
    } else if (platform === 'ios') {
        // 检查iOS权限状态
        getContactsHandle(); // iOS 直接调用
    }
}


const getContactsHandle = () => {
    // 获取系统通讯录
    plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => {
        // 查找联系人
        addressbook.find(["displayName", "phoneNumbers"], (contacts: any) => {
            // let newList: contactType[] = []
            let indexList: IndexListType[] = []
            let indexListSource: indexListSourceType[] = []
            contacts.forEach((item: any) => {
                if(item.phoneNumbers && item.phoneNumbers.length > 0) {
                    let letter = '#';
                    if(item.displayName) {
                        letter = Pinyin.GetJP(item.displayName[0]).toUpperCase();
                    } else {
                        console.log(item);

                    }
                    item.phoneNumbers.forEach((phone: any) => {
                        let phoneItem = {
                            letter,
                            id: phone.id || Math.random().toString(32).slice(2),
                            name: item.displayName || '未知名称',
                            mobile: phone.value,
                            type: phone.type
                        }
                        // newList.push(phoneItem)
                        let letterIndex = indexListSource.findIndex(i => i.letter == letter)
                        if(letterIndex == -1) {
                            indexListSource.push({
                                letter,
                                data: [phoneItem]
                            })
                        } else {
                            indexListSource[letterIndex].data.push(phoneItem)
                        }
                    })
                }
            })

            // 根据字母县后顺序排序
            indexListSource.sort((a: indexListSourceType, b: indexListSourceType) => {
                return a.letter.localeCompare(b.letter)
            })
            contactSourceList.value = indexListSource
            console.log(indexList );
        }, (e) => {
            console.log('查找联系人失败: ' + e.message);
            handleContactError(e)
        }, { multiple: true });
    }, (e) => {
        console.log('获取通讯录失败: ' + e.message);
        uni.navigateBack()
        handleContactError(e)
    })
}

// 统一处理错误
const handleContactError = (e) => {
    if (e.code === 20) {
        Interact.toast('您拒绝了通讯录权限，请在设置中开启');
    } else {
        Interact.toast('获取通讯录失败: ' + e.message);
    }
}


</script>
<style lang="scss" scoped>
.contact{
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    .container{
        flex: 1;
        height: 0;
        width: 100%;
        position: relative;
    }
}

</style>